define([ "jquery","plugin/jquery-scrollbar/jquery.mCustomScrollbar",
         "comm","site_tip","plugin/jquery.form","upload/comm","files/file","mustache"],  
         function($,mCustomScrollbar,comm,Site_tip,Jform, uploadCom,File,Mustache) {
	var Files; 
	require(['files/main'],function (f){
		Files = f;
	});
	
	var site_tip = new Site_tip();
	
	function Upload() {
		this.container = $("#upload_form");
		this.upload_num = 0;
		this.uploaded_num = 0;
		this.upload_total = 0;
		this.error_len = 0;
		this.arr_len = 0;
		this.jqXHR_me = null;
		this.fileName = '';
		this.changeFlag = 0;
		this.clearProId = 0;
		this.isScroll = false;
		this.is_over = false;
		this.pro_req = new Array();
		this.isCom = new Array();
	}
	
	Upload.prototype.init = function() {
		comm.loadCss("/static/js/jquery/jquery-scrollbar/jquery.mCustomScrollbar.css");
		this._bindUI();
		this.jqXHR_me = new Array();
	}
	
	Upload.prototype._bindUI = function() {
		var that = this;
		this.container.off().on("change","#file_add", function() {
			var fileName = $(this).val();
			var arr = fileName.split("\\");
			if (arr.length > 0) {
				fileName = arr[arr.length - 1];
			}
			var fileInput = $("#file_add");
			var fileSize = 0;
			if (fileInput[0].files && fileInput[0].files[0]) {
				fileSize = fileInput[0].files[0].size;
				if (fileSize <= 0) {
					// alert("上传文件不允许为空，请重新上传!");
					site_tip.setContent("上传文件为空文件", true, false);
					
					return;
				}
			}
			
			if (uploadCom.check_type(fileName)) {
				that.create_uuid(fileName);
			}else{
				var msg = "上传的文件类型不支持，<a href='/helpcenter?active=1' class='outer-tip' target='_blank'>查看帮助</a>";
				site_tip.setContent(msg, true, false);
			}
		});
		
		$("#processWindow").off();
		// 显示上传进度框
		$("#processWindow").on("mouseenter",function(e) {
			if (that.is_over)
				return;
			if ($("#upload-procr-menu").css("display") == "none")
				return;
			$('#upload-procr').stop(true, true);
			$('#upload-procr').slideDown();
			that.is_over = true;
			that.pro_stop_animal.apply(that);
		});

		// 隐藏上传进度框
		$("#processWindow").on("mouseleave",function(e) {
			if (!that.is_over) {
				return;
			}
			that.is_over = false;
			that.proWindow_close.apply(that);
			/*
			that.pro_start_animal.apply(that);
			*/
		});
		//console.log("onbeforeunload");
		// 离开页面时保存文档
		window.onbeforeunload = function() {
			if (that.changeFlag == true) {
				// 如果changeFlag的值为true则提示
				return '该操作会导致文件上传中断，是否继续';
			}

		}
	}
	
	Upload.prototype.create_uuid = function(fileName) {
		this.arr_len += 1;
		var file = new File();
		file.name = fileName;
		file.index = this.arr_len;
		file.uuid = this.NewGuid();

		this.upload_submit(file);
		$('#file_add').val("");
	}
	
	Upload.prototype.upload_submit = function(file) {
		var s_id = $("#s_id").val()
		$("#upload_form").attr("action","/file_s/u?x-progress-id="+file.uuid+"&_rsvd_index="+this.arr_len+"&t="+s_id+"&p="+$("#wfo").data("last_pid"));
		var that = this;
		var options = {
			target : '#output' + (that.arr_len),
			type : "POST",
			contentType: "application/x-www-form-urlencoded; charset=utf-8", 
			dataType : 'json',
			beforeSend : function(jqXHR, settings) { // 开始上传
				that.pro_stop_animal();
				that.upload_num += 1;
				that.upload_total += 1;
				that.jqXHR_me[file.index] = jqXHR;
				var bb = that.jqXHR_me[file.index];
				$("#processWindow").css('display', 'block');
				$("#upload-procr-menu").css('display', 'inline-block');
				$("#upload-procr").css("display", "block");
				that.uploading_status.apply(that);
				that.add_pro.apply(that,[file]);
			},
			success : function(jsonData) {
				that.isCom[jsonData._rsvd_index] = true;
				var data = jsonData.data;
				that.uploaded_num += 1;
				var item = $("#procr_panel").find("div[f_index="+jsonData._rsvd_index+"]");
				if (jsonData.ret > -1) {
					that.uploading_err.apply(that,[jsonData._rsvd_index,item]);
					return;
				}
				if (that.pro_req[jsonData._rsvd_index] != "undefined"
					&& that.pro_req[jsonData._rsvd_index] != null) {
					clearInterval(that.pro_req[jsonData._rsvd_index]);
				}

				
				
				item.find(".bar").css('width', '100%');
				item.find(".icon-del").parent().css("display","none");
				item.attr("status","0");

				setTimeout(that._show_suc_statu.apply(that,[jsonData._rsvd_index]), 1000);

				if (that.upload_num > 0) {
					that.upload_num -= 1;
				}
				that.uploading_status.apply(that);

				var e = jQuery.Event("fileUpload.add");
				e.file = data;
				that.container.trigger(e);
				/*
				that.pro_stop_animal.apply(that);
				that.pro_start_animal.apply(that);
				*/
				$('body').data('update', 1);
			},
			error : function(xhr, textStatus, errorThrown, target) {
				if (textStatus == "aborted") {
					return;
				}
				var index = target.charAt(target.length - 1);
				var aa = that.jqXHR_me;
				if (that.jqXHR_me[index]) {
					that.jqXHR_me[index].abort();
				}
				
				var item_msg = "无法连接到服务器";
				console.log(xhr);
				if (xhr.status == 411) {
					item_msg = "上传的文件为空文件";
				}else if (xhr.status == 415) {
					item_msg = "上传的文件类型不支持，<a href='/helpcenter?active=1' class='outer-tip' target='_blank'>查看帮助</a>";
				}else if (xhr.status == 413) {
					item_msg = "空间不足，请扩容或者删除历史文件再上传";
				}else if (err.status == 408) {
					item_msg = "上传超时";
				}else if (err.status == 500) {
					item_msg = "系统繁忙";
				}
					
				tip_msg = item_msg;
				var item = $("#procr_panel").find("div[f_index="+index+"]");
				that.uploading_err.apply(that,[index,item]);

				
				item.find(".icon-err").attr("title", item_msg);
				var percent = item.find(".percent");
				percent.text(item_msg);
				percent.addClass("err");
				
				var e = jQuery.Event("fileUpload.err");
				e.msg = tip_msg;
				that.container.trigger(e);
				
				item.attr("status","1");
				
				site_tip.setContent(tip_msg, true, false);
			}
		};
		$("#upload_form").ajaxSubmit(options);

		changeFlag = true;
		return false;
	}
	
	Upload.prototype.add_pro = function(file) {
		f_index = file.index;
		var that = this;
		
		var view = {
			"index" : f_index,
			"type" : comm.get_file_type(file.name),
			"name" : file.name
		};
		var tmpl = $('#proTpl').html();
		var item_text = Mustache.render(tmpl, view);
		$('#procr_panel').append(item_text);
		
		var item = $("#procr_panel").find("div[f_index="+f_index+"]");
		if (f_index % 2 == 0) {
			item.css("background-color", "#fafafb");
		}

		var pro_del = item.find(".icon-del");
		pro_del.click(function() {
			that.upload_num -= 1;
			that.upload_total -= 1;
			var index = parseInt($(this).parents(".item").attr("f_index"));
			if (that.jqXHR_me[index]) {
				that.jqXHR_me[index].abort();
			}
			item.remove();
			
			if (that.pro_req[index] != "undefined" && that.pro_req[index] != null) {
				clearInterval(that.pro_req[index]);
			}
			that.pro_req[index] = null;
			
			that.uploading_status.apply(that);
		});
		
		var errs = $('#procr_panel').find(".item[status='1']");
		$(errs).each(function(){
			var filename = $(this).find(".name").text();
			if(filename == file.name){
				that.upload_num -= 1;
				that.upload_total -= 1;
				var index = $(this).attr("f_index");
				if (that.jqXHR_me[index]) {
					that.jqXHR_me[index].abort();
				}
				$(this).remove();	
			}
		});
		
		if (!that.isCom[f_index]) {
			that.pro_req[f_index] = setInterval(that._get_progress_data(file.uuid,
					f_index), 5000);
		}
		
		that.checkPro.apply(that);
	}
	
	Upload.prototype.checkPro = function() {
		if($("#upload-procr").height()<200){
			var item = $("#procr_panel").find(".item");
			var p_height= item.size()*46;
			$("#upload-procr").height(p_height);
		} else if ($("#upload-procr").height() > 200 && !this.isScroll) {
			$("#upload-procr").height(229);
			this.isScroll = true;
			$("#upload-procr").mCustomScrollbar({
				theme : "minimal"
			});
		} else{
			var item = $("#procr_panel").find(".item");
			var p_height= item.size()*46;
			$("#upload-procr").height(p_height);
			
			if($("#upload-procr").height() > 200){
				$("#upload-procr").height(229);
			}
		}
	}
	
	Upload.prototype._get_progress_data = function(f_uuid, f_index) {
		var that = this;
		return function() {
			that.get_progress_data.apply(that,[f_uuid, f_index]);
		}
	}
	
	Upload.prototype.get_progress_data = function(uuid, f_index){
		var that = this;
		$.ajax({
			type : "GET",
			url : "/file_s/qp",
			data: {"_rsvd_index" : f_index},
			dataType : "json",
			beforeSend : function(req) {
				req.setRequestHeader("X-Progress-ID", uuid);
			},
			success : function(josnData) {
				 if (that.isCom[josnData._rsvd_index] == true) {
					return;
				 }
				data = josnData.data;
				var progress;
				if (josnData.ret != -1) {
					return;
				}
				if (data) {
					var tet = data.received;
					var te = data.size;
					if (data.received && data.size) {
						progress = that.changeTwoDecimal_f(data.received/ data.size) * 100;
					}
				}
				
				var item = $("#procr_panel").find("div[f_index="+josnData._rsvd_index+"]");
				item.find(".bar").css('width',progress + '%');
				var file_pro = item.find(".percent");
				if (progress != 100) {
					$(file_pro).html(progress + '%');
				}
			},
			complete : function(josnData) {
//				alert("complete=" + xml.responseText);
			},
			failure : function(josnData) {
//				alert("in failure");
			}
		});

	}
	
	Upload.prototype.changeTwoDecimal_f = function(x){
		var f_x = parseFloat(x);
		if (isNaN(f_x)) {
			alert('function:changeTwoDecimal->parameter error');
			return false;
		}
		var f_x = Math.round(x * 100) / 100;
		var s_x = f_x.toString();
		var pos_decimal = s_x.indexOf('.');
		if (pos_decimal < 0) {
			pos_decimal = s_x.length;
			s_x += '.';
		}
		while (s_x.length <= pos_decimal + 2) {
			s_x += '0';
		}
		return s_x;
	}
	
	Upload.prototype.uploading_status = function() {

		if (this.upload_num > 0) {
			$("#processWindow").find(".loading").css("display", "block");
			$("#upload-procr-menu")
					.html("已完成 " + this.uploaded_num + "/" + this.upload_total);
			return;
		}
		
		$("#processWindow").find(".loading").css("display", "none");
		this.changeFlag = false;
		
		this.changeFlag = false;
		var itemLen = $("#procr_panel").children().length;
		if (itemLen == 0) {
			this.pro_stop_animal();
			this.clearPro();
			return;
		}
		
		
		if (this.error_len == this.arr_len) {
			$("#upload-procr-menu")
				.html(this.arr_len+"个文件上传失败&nbsp;&nbsp;<a href='#' id='pro-clean' class='inner-tip'>清空</a>");
		}else if(this.error_len > 0 && this.error_len <this.arr_len){
			$("#upload-procr-menu")
				.html(uploaded+"个文件上传成功，"+failed+"个失败&nbsp;&nbsp;<a href='#' id='pro-clean' class='inner-tip'>清空</a>");
		}else {
			$("#upload-procr-menu")
				.html("上传完毕");
		}
		
		var that = this;
		$("#pro-clean").off().on("click", function(e) {
			comm.stopEvent(e);
			
			that.pro_stop_animal();
			that.clearPro();
			
			if($(this).text() == "查看"){
				var files = new Files();
				files.listToTop();
				
				var e = jQuery.Event("fileUpload.see");
				that.container.trigger(e);
			}
		});
	}
	
	Upload.prototype.pro_stop_animal = function() {
		if (this.clearProId != null || this.clearProId != undefined) {
			clearTimeout(this.clearProId);
			this.clearProId = null;
		}
	}
	
	Upload.prototype._clearPro = function() {
		var that = this;
		return function() {
			that.clearPro();
		}
	}
	
	
	Upload.prototype.clearPro = function() {
		if (this.upload_num > 0) {
			return;
		}
		this.resetData();
		this.clearProId = null;
	}
	
	Upload.prototype.resetData = function() {
		$("#upload-procr").css('display', 'none');
		$("#upload-procr-menu").css('display', 'none');
		$("#upload-procr-menu").find("a").remove();
		$("#upload-procr-menu").html("");
		$("#upload-procr").height(0);
		this.upload_num = 0;
		this.uploaded_num = 0;
		this.upload_total = 0;
		this.error_len = 0;
		this.arr_len = 0;
		this.jqXHR_me = new Array();
		this.isCom = new Array();

		$("#procr_panel").find(".item").remove();
	}
	
	Upload.prototype.retUploadData = function() {
		this.upload_num = 0;
		this.uploaded_num = 0;
		this.upload_total = 0;
		this.error_len = 0;
		this.jqXHR_me = new Array();
	}
	
	Upload.prototype.proWindow_close = function(){
		$('#upload-procr').stop(true, true);
		$('#upload-procr').hide();
	}
	
	Upload.prototype.uploading_err = function(f_index,item) {
		this.upload_num -= 1;
		this.uploaded_num += 1;
		this.error_len += 1;
		item.find(".icon-del").parent().css("display", "none");
		item.find(".icon-err").parent()
				.css("display", "table-cell");
		item.find(".bar").width(0);
		this.uploading_status();
		item.find(".percent").html('');
		
		clearInterval(this.pro_req[f_index]);
		this.pro_req[f_index] = null;
	}
	
	Upload.prototype._show_suc_statu = function(index) {
		var that = this;
		return function() {
			that.show_suc_statu(index);
		}
	}
	
	Upload.prototype.show_suc_statu = function(index) {
		var item = $("#procr_panel").find("div[f_index="+index+"]");
		var file_pro = item.find(".percent");
		$(file_pro).html('');

		item.find(".icon-suc").parent().css("display", "table-cell");

		item.find(".bar").css('width', '0');
	}
	
	/*
	 * 创建guid
	 */
	Upload.prototype.NewGuid = function() {
		var S4 = function() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		}
		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4()
				+ S4() + S4());
	}
	
	Upload.prototype.pro_start_animal = function() {
		if($("#waterfall").height()<$("#mypage").height()){
			this.clearProId = setTimeout(this._clearPro(), 800000);
		}
	}
	
	return Upload;
});